package net.huashitong.synthetical.newSupervision.service;

import com.sirdc.modules.core.dao.BaseDao;
import com.sirdc.modules.core.filter.Paging;
import com.sirdc.modules.sys.base.StringPKService;
import com.sirdc.modules.sys.dao.SysUserDao;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.service.SysTableService;
import com.sirdc.modules.sys.util.SysUserUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.supervision.task.service.SMSUtilService;
import net.huashitong.synthetical.newSupervision.dao.TaskMessageDao;
import net.huashitong.synthetical.newSupervision.dao.TaskNewDao;
import net.huashitong.synthetical.newSupervision.dao.TaskWorkableDao;
import net.huashitong.synthetical.newSupervision.entity.*;
import net.huashitong.synthetical.newSupervision.filter.TaskNewFilter;
import net.huashitong.synthetical.newSupervision.util.HolidayUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * Created with IntelliJ IDEA.
 * User: ling
 * Date: 2019/7/2
 * Time: 20:47
 * To change this template use File | Settings | File Templates.
 * Description:
 */
@Service
public class TaskNewService extends StringPKService<TaskNew> {

    @Autowired
    private TaskNewDao dao;

    @Autowired
    private TaskSendService taskSendService;

    @Autowired
    private TaskWorkableDao taskWorkableDao;
    @Autowired
    private TaskMessageDao taskMessageDao;

    @Autowired
    private SysUserDao userDao;

    @Autowired
    private TaskLogService taskLogService;

    @Autowired
    private SysTableService tableService;

    @Autowired
    private TaskBackService taskBackService;

    @Autowired
    private TaskCopeToService taskCopeToService;

    @Override
    protected void beforeSave(TaskNew obj) {
        obj.setSysId(tableService.updateMaxSysId("t_task_new", null));
    }

    SimpleDateFormat simdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat simdate1 = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 条件查询主要方法
     */
    public List<TaskNew> getProjectList(TaskNewFilter taskNewFilter) {
        return dao.getProjectList(taskNewFilter);
    }

    /**
     * 保存新建任务
     *
     * @param filter
     */
    public void saveProject(TaskNewFilter filter) {
        TaskNew taskNew = new TaskNew();
        BeanUtils.copyProperties(filter, taskNew);
        String deptId = SysUserUtils.getDeptId();
        //设置任务督查组单位id
        taskNew.setInspectionId(deptId);
        // 任务状态
        taskNew.setType("0");
        // 数据有效性
        taskNew.setStatus("1");

        try {
            Date date = new Date();
            int i = Integer.parseInt(filter.getDateTime());
            //设置任务时限 将天数转换成日期
            List<String> holidays = new ArrayList<>();
            Date datetime = HolidayUtils.getScheduleActiveDate(date, holidays, i);
            String format = simdate1.format(datetime);
            taskNew.setDateTime(format);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        this.save(taskNew);

        //记录任务日志
        TaskLog taskLog = new TaskLog();
        taskLog.setTableId(taskNew.getSysId());
        taskLog.setProcesses("任务立项");
        String userId = SysUserUtils.getUserId();
        SysUser user = userDao.getById(userId);
        taskLog.setTransactor(user.getName());
        taskLog.setTransactorTel(user.getMobile());
        taskLog.setDatetime(simdate.format(new Date()));

        taskLogService.save(taskLog);

        List<TaskSend> list = filter.getList();
        String taskId = taskNew.getSysId();
        if (!list.isEmpty()) {
            for (TaskSend taskSend : list) {
                if (StringUtils.isNotBlank(taskSend.getUserId())) {
                    taskSend.setDateTime(taskNew.getDateTime());
                    taskSend.setTaskId(taskId);
                    // 任务状态
                    taskSend.setType("0");
                    // 数据有效性
                    taskSend.setStatus("1");
                    taskSendService.save(taskSend);
                }
            }
        }
        //抄送任务保存
        List<String> copeIdList = filter.getCopeIdList();//
        if (copeIdList != null && copeIdList.size() > 0) {
            TaskCopeTo taskCopeTo = new TaskCopeTo();
            for (String id : copeIdList) {
                taskCopeTo.setTaskId(taskId);
                taskCopeTo.setCountyLeaderId(id);
                //保存抄送
                taskCopeToService.save(taskCopeTo);
            }
        }

        //记录任务日志
        TaskLog taskLog2 = new TaskLog();
        taskLog2.setTableId(taskNew.getSysId());
        taskLog2.setProcesses("督查人员");
        taskLog2.setTransactor(taskNew.getOperator());
        taskLog2.setTransactorTel(taskNew.getOperatorTel());
        taskLog2.setDatetime(simdate.format(new Date()));
        taskLogService.save(taskLog2);
    }


    /**
     * 修改任务
     *
     * @param filter
     */
    public void updateTask(TaskNewFilter filter) {
        TaskNew taskNew = dao.getById(filter.getSysId());

        //判断是否更改过时间

        if (!taskNew.getDateTime().equals(filter.getDateTime())) {

            //如果日期不相等表示改过,将天数转换成日期赋值
            try {
                Date date = new Date();
                int i = Integer.parseInt(filter.getDateTime());
                //设置任务时限 将天数转换成日期
                List<String> holidays = new ArrayList<>();
                Date datetime = HolidayUtils.getScheduleActiveDate(date, holidays, i);
                String format = simdate1.format(datetime);
                filter.setDateTime(format);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

//        如果没有改变,直接赋值
//        BeanUtils.copyProperties(filter, taskNew);
//        String deptId = SysUserUtils.getDeptId();
        //设置任务督查组单位id
//        taskNew.setInspectionId(deptId);
        if (StringUtils.isNotBlank(filter.getDateTime())) {
            taskNew.setDateTime(filter.getDateTime());
        }
        if (StringUtils.isNotBlank(filter.getOperator())) {
            taskNew.setOperator(filter.getOperator());
        }
        if (StringUtils.isNotBlank(filter.getOperatorId())) {
            taskNew.setOperatorId(filter.getOperatorId());
        }
        if (StringUtils.isNotBlank(filter.getLeader())) {
            taskNew.setLeader(filter.getLeader());
        }
        if (StringUtils.isNotBlank(filter.getTaskName())) {
            taskNew.setTaskName(filter.getTaskName());
        }
        if (StringUtils.isNotBlank(filter.getComment())) {
            taskNew.setComment(filter.getComment());
        }
        if (StringUtils.isNotBlank(filter.getContent())) {
            taskNew.setContent(filter.getContent());
        }
        if (StringUtils.isNotBlank(filter.getFile())) {
            taskNew.setFile(filter.getFile());
        }
        if (StringUtils.isNotBlank(filter.getOperatorTel())) {
            taskNew.setOperatorTel(filter.getOperatorTel());
        }


        // 数据有效性
        taskNew.setStatus("1");
        this.update(taskNew);
        //更新该任务下原单位的任务时限
        List<TaskSend> sendList = taskSendService.queryByTaskId(taskNew.getSysId());
        for (TaskSend taskSend : sendList) {
            taskSend.setDateTime(filter.getDateTime());
        }

        //记录任务日志
        TaskLog taskLog = new TaskLog();
        taskLog.setTableId(taskNew.getSysId());
        taskLog.setProcesses("任务修改");
        String userId = SysUserUtils.getUserId();
        SysUser user = userDao.getById(userId);
        taskLog.setTransactor(user.getName());
        taskLog.setTransactorTel(user.getMobile());
        taskLog.setDatetime(simdate.format(new Date()));

        taskLogService.save(taskLog);

        //派发任务保存
        List<TaskSend> list = filter.getList();
        String taskId = taskNew.getSysId();
        if (list != null && list.size() > 0) {
            for (TaskSend taskSend : list) {
                if (StringUtils.isNotBlank(taskSend.getUserId())) {
                    taskSend.setDateTime(taskNew.getDateTime());
                    taskSend.setTaskId(taskId);
                    // 任务状态
                    taskSend.setType("0");
                    // 数据有效性
                    taskSend.setStatus("1");
                    taskSendService.save(taskSend);

                    // 主任务状态
                    taskNew.setType("0");
                    this.update(taskNew);
                }
            }
        }



        //记录任务日志
        TaskLog taskLog2 = new TaskLog();
        taskLog2.setTableId(taskNew.getSysId());
        taskLog2.setProcesses("督查人员");
        taskLog2.setTransactor(taskNew.getOperator());
        taskLog2.setTransactorTel(taskNew.getOperatorTel());
        taskLog2.setDatetime(simdate.format(new Date()));

        taskLogService.save(taskLog2);
    }

    @Override
    protected BaseDao<TaskNew, String> getDao() {
        return this.dao;
    }

    /**
     * 批量删除任务
     *
     * @param ids
     */
    public void deleteTask(List<String> ids) {
        dao.batchDelete(ids);
        taskSendService.deleteByTaskIds(ids);
        taskWorkableDao.deleteByTaskIds(ids);
        taskLogService.deleteByTaskIds(ids);
        taskMessageDao.deleteByTaskIds(ids);

    }

    /**
     * 办结评价
     *
     * @param filter
     */
    public void updateComment(TaskNewFilter filter) {
        TaskNew taskNew = dao.getById(filter.getSysId());
        taskNew.setType(filter.getType());
        List<TaskSend> sendList = taskSendService.queryByTaskId(filter.getSysId());
        //将派送的任务状态改为与主任务一样
        for (TaskSend taskSend : sendList) {
            taskSend.setType(filter.getType());
            taskSendService.update(taskSend);
        }
        taskNew.setComment(filter.getComment());
        dao.update(taskNew);

        //任务流程记录
        TaskLog taskLog = new TaskLog();
        taskLog.setProcesses("办结评价");
        taskLog.setTableId(filter.getSysId());
        String userId = SysUserUtils.getUserId();
        SysUser user = userDao.getById(userId);
        taskLog.setTransactor(user.getName());
        taskLog.setTransactorTel(user.getMobile());
        taskLog.setDatetime(simdate.format(new Date()));
        taskLogService.save(taskLog);

    }

    /**
     * 根据id查询任务
     *
     * @param ids
     * @return
     */
    public List<TaskNew> getTaskNewByIds(List<String> ids) {
        List<TaskNew> list = new ArrayList<>();
        for (String id : ids) {
            TaskNew taskNew = dao.getById(id);
            list.add(taskNew);
        }
        return list;
    }


    /**
     * 导出督查任务报表
     *
     * @param filter
     * @return
     */
    public HSSFWorkbook getTaskExcel(TaskNewFilter filter) {
        Paging page = new Paging();
        page.setSortCol("sysId");
        page.setSortVal("desc");
        page.setPageSize(300);
        filter.setPaging(page);
        List<TaskNew> taskNewList = this.getTaskNewByIds(filter.getSysIds());
        //创建一个对应的Excel文件
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("督查情况表");//创建Excel中的sheet
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = workbook.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//居中格式
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框

        HSSFCellStyle style2 = workbook.createCellStyle();
        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        style2.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
        style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
        style2.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
        style2.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
        //------列-------
      /*  CellRangeAddress cellRangeAddress0 = new CellRangeAddress(1, 1, 0, 0);
        sheet.addMergedRegion(cellRangeAddress0);*/
        HSSFCell cell1 = row.createCell(0);
        cell1.setCellValue("序号");
        cell1.setCellStyle(style);
        List<String> headers = new ArrayList<>();
        headers.add("纪要名称");
        headers.add("议题内容");
        headers.add("议定事项");
        headers.add("承办单位");
        headers.add("督办结果");
        headers.add("办结情况");
        for (int i = 0; i < headers.size(); i++) {
            HSSFCell cell = row.createCell(i + 1);
            cell.setCellValue(headers.get(i));//设置表头
            cell.setCellStyle(style);
            sheet.autoSizeColumn((short) i);
            sheet.setColumnWidth(i, sheet.getColumnWidth(i) * 15 / 10);
        }
        String taskName = "";  //纪要名称
        String remark = "";  //议题内容
        String departName = ""; //承办单位
        String type = "";   //办结情况
        int rows = 1;
        for (int i = 0; i < taskNewList.size(); i++) {
            taskName = taskNewList.get(i).getTaskName();//纪要名称
            row = sheet.createRow(rows);
            HSSFCell numCell = row.createCell(0);
            numCell.setCellValue(rows);//设置序号
            numCell.setCellStyle(style);//居中样式
            HSSFCell nameCell = row.createCell(1);
            nameCell.setCellValue(taskName);
            nameCell.setCellStyle(style2); //样式
            List<TaskSend> taskSendList = taskSendService.queryByTaskId(taskNewList.get(i).getSysId());
            if (taskSendList.size() > 0) {
                for (int n = 0; n < taskSendList.size(); n++) {
                    HSSFCell remarkCell = row.createCell(2);
                    remarkCell.setCellValue(taskSendList.get(n).getRemark());//设置议题内容
                    remarkCell.setCellStyle(style);//样式居中
                    row.createCell(3).setCellStyle(style);//创建空单元格,设置样式
                    row.createCell(4).setCellValue(taskSendList.get(n).getDepartName());//设置承办单位
                    //查询当前单位的承办结果
                    List<TaskBack> backList = taskBackService.getBySendId(taskSendList.get(n).getSysId());
                    //将反馈结果进行拼接
                    String content = "";  //督办结果
                    for (TaskBack taskBack : backList) {
                        String str = taskBack.getTitle() + "  " + taskBack.getContent() + "\n";
                        content = content + str;
                    }
                    HSSFCell contentCell = row.createCell(5);
                    contentCell.setCellValue(content);
                    contentCell.setCellStyle(style2);  //设置样式
                    String s = taskNewList.get(i).getType();
//                    0:待签收 1:待反馈 2:已反馈 3:办结 4:未办结
                    if ("0".equals(s)) {
                        type = "待签收";
                    }
                    if ("1".equals(s)) {
                        type = "待反馈";
                    }
                    if ("2".equals(s)) {
                        type = "已反馈";
                    }
                    if ("3".equals(s)) {
                        type = "办结";
                    }
                    if ("4".equals(s)) {
                        type = "未办结";
                    }
                    if ("5".equals(s)) {
                        type = "逾期";
                    }
                    HSSFCell typeCell = row.createCell(6);
                    typeCell.setCellValue(type);
                    typeCell.setCellStyle(style);//样式居中
                    rows++;
                    row = sheet.createRow(rows);
                }

                //设置合并单元格
                CellRangeAddress region = new CellRangeAddress(rows - taskSendList.size(), rows - 1, 1, 1);
                CellRangeAddress region1 = new CellRangeAddress(rows - taskSendList.size(), rows - 1, 0, 0);
                sheet.addMergedRegion(region);
                sheet.addMergedRegion(region1);
            }
        }
        return workbook;
    }
}
